package click

import java.util.Calendar
// ip纪录表，每一次成功
// 或不成功都纪录在案
class Ip {
    String source // 贡献的机器 mac
    String address
    Date lastTime = new Date()
    Boolean success = false

    static constraints = {
        source(size:1..50,blank:false )
        address(size:1..15,blank:false )
        lastTime()
        success()
    }

    String toString(){
        "${source} : ${address}"
    }

    static int lastIp(String ip){
        def calendar=Calendar.getInstance();   

        calendar.add(Calendar.HOUR_OF_DAY ,1)
        def end = calendar.getTime()
        calendar.add(Calendar.HOUR_OF_DAY ,-25)
        def start = calendar.getTime()
        def c = Ip.createCriteria()

        return c.count {
            and{
                between('lastTime', start, end)
                eq('success', true)
                eq('address', ip)
            } 
        }
        //return  Ip.countByAddressAndLastTimeBetween( ip , start , end)
    }

    static String statistics(){
        def result = ''
        Calendar   calendar   =   Calendar.getInstance();   //获取日历  
        calendar.set(Calendar.HOUR_OF_DAY ,0)
        calendar.set(Calendar.MINUTE,0)
        def end = calendar.getTime()
        calendar.add(Calendar.DAY_OF_MONTH,-1) 
        def start = calendar.getTime()
        def countTotal
        println  "start - end : [ ${start} - ${end}]"
        countTotal = Ip.createCriteria().count{  
                between('lastTime', start, end) 
        }
        result += "total : ${countTotal}\n"


        countTotal = Ip.createCriteria().count{  
                between('lastTime', start, end)
                eq('success', true)  
         
        }
        result += "totalTrue : ${countTotal}\n"


        countTotal =Ip.createCriteria().count{ 
            
                between('lastTime', start, end)
                eq('success', false)  
        }
        result += "totalFalse : ${countTotal}\n"


        Machine.list().each{ machine ->
            countTotal = Ip.createCriteria().count{ 
                 
                    between('lastTime', start, end) 
                    eq('source', machine.mac)  
            }

            result += "${machine.name} total : ${countTotal}\n"
        }

        return result
    }
}
